# coding: utf8
"""
工具杂项
:author: Tony 2015/7/12
"""
__author__ = 'Tony'

import logging


logger = logging.getLogger('default')


def transform_model_to_proxy(origin, proxy_class):
    """
    将原model对象转换指定的proxy对象
    :param origin: <object: 原始model对象>
    :param proxy_class: <class: Proxy Model类>
    :return: <object: 代理对象>
    :author: gzj 20150712
    """
    proxy = proxy_class()
    for field in origin._meta.fields:
        setattr(proxy, field.name, getattr(origin, field.name))
    return proxy


def base64_decode(content):
    """
    解码base64字符串
    :param content: <str: base64>
    :return: <bytes>
    :author: gzj 20150714
    """
    from base64 import b64decode

    b64content = content.split(',')[1]
    lens = len(b64content)
    padding = '=' * ((3 - lens % 3) % 3)
    b64content += padding
    decoded_content = b64decode(b64content)
    return decoded_content


def get_cursor(dbname='default'):
    """
    获取数据库的游标
    :param dbname: <str>
    :return: <Cursor>
    :author: gzj 20150714
    """
    from django.db import connections

    return connections[dbname].cursor()


def compare_version(src, dst):
    """
    比较版本号
    :param src: 基版本号
    :param dst: 对照版本号
    :return: 1：src > dst, 0: src = dst, -1: src < dst
    :rtype: int
    :author: Unknown @ 20150629
    """
    from distutils.version import LooseVersion
    src_v = LooseVersion(src)
    dst_v = LooseVersion(dst)
    if src_v < dst_v:
        return -1
    elif src_v == dst_v:
        return 0
    else:
        return 1


def get_real_ip(request):
    """
    获取真实的IP地址
    :return: <str: real_ip>
    """
    real_ip = request.META.get('HTTP_X_FORWARDED_FOR', '')
    if real_ip:
        real_ip = real_ip.split(",")[0]
    else:
        real_ip = request.META.get('REMOTE_ADDR', '')
    return real_ip


def make_common_redirect(msg='', url='/'):
    """
    生成跳转Response对象
    :param msg: 跳转消息
    :param url: 跳转链接, 默认跳转到主页
    :return: Object
    :rtype: HttpResponseRedirect
    :author: gzj 20150729
    """
    from django.http import HttpResponseRedirect
    from django.core.urlresolvers import reverse

    return HttpResponseRedirect(
        reverse('dayi.common_redirect')
        + '?redirect_url={0}&redirect_msg={1}'.format(url, msg)
    )


def rest_with_transaction(status, msg='', data={}, commit=False):
    """
    生成带事务控制的rest响应字典
    :param commit: 事务是否提交, 默认不提交
    :author: Unknown @ 20150606
    """
    return {
        'status': status,
        'msg': msg,
        'data': data,
        'commit': commit
    }


def pack_rest(status, msg='', data={}):
    """
    生成rest响应字典
    :param status: int 状态码
    :param msg: str 消息
    :param data: dict 数据
    :return: {retcode, msg, data}
    :rtype: json str
    :author: Unknown
    :create: 20150417
    """
    return {
        'status': status,
        'msg': msg,
        'data': data
    }


def pack_rest_res(status, msg='', data={}):
    """
    生成rest接口对象
    :param status: <int: status code>
    :param msg: <str>
    :param data: <object: json>
    :return: <HttpResponse>
    :authro: gzj 20150715
    """
    import json
    from django.http import HttpResponse
    return HttpResponse(json.dumps(pack_rest(status, msg, data)))


def request_to(url):
    """
    快速GET请求
    :param url: <str>
    :return: <str>
    """
    import urllib2
    try:
        req = urllib2.Request(url)
        return urllib2.urlopen(req).read()
    except:
        logger.exception('request_to %s' % url)
        return None
